package com.dat255.tentatime;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dat255.tentatime.es.ExternalStorage;


/**
 * This activity is our main activity
 * The task for this activity is to assist  the user to retrieve
 * general information about an exam for a course at Chalmers University
 * @author Joseph
 * @version 2.3
 */

// TODO: Some Toast msg needs to be moved to string res
public class FindActivity extends Activity implements OnClickListener {
	
	//The input field for the textbox
	private EditText editSearch;
	// The search button
	private Button buttonFind;
	//Error msg
	private String err_msg = "";
	//Dialog ID
	private static final int DIALOG_ID = 47;
	//variable to login/out
	//private UserState app = ((UserState)FindActivity.this.getApplication());

	
	
    /** 
     * Called when the activity is first created. 
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        
    	
    	super.onCreate(savedInstanceState);
    	//Sets the layout of the activity
        setContentView(R.layout.find);
        //Attach input/output controls 
        this.AttachGUIcomponents();
        //Initiate listener for the button
        buttonFind.setOnClickListener(this);
        
  
    }
  

    /**
     * This method is invoked when the user presses the button
     * The method will validate the input-data and assist the user 
     * if wrong information was entered
     */
	@Override
	public void onClick(View v) {
		//Save the user entered data
		String userdata = editSearch.getText().toString();
		
		//Check if there is a valid internet connection
		if(InputUtility.connectedToTheInternet(this)){
		
				// 1. Validate user entered data
				// 2. Check if the entered data was a course id or a course name
				if(InputUtility.validateCourseID(userdata)){
					
					
					
					showDialog(DIALOG_ID);
				    new SearchForexam().execute(InputUtility.convertIdToUpperCase(userdata));
						
				}else if(InputUtility.validateName(userdata)){
					
					
					showDialog(DIALOG_ID);
				    new SearchForexams().execute(InputUtility.convertStringToLowerCase(userdata));
						
				}else{
					
				// 3. The user data was incorrect, a message will inform the user	
					Toast.makeText(this,R.string.toastWrongInput,Toast.LENGTH_LONG).show();
					
				}
		}else{
			// 4. The phone is not connected to the internet, no network connection
			Toast.makeText(this,R.string.toastnoInterner,Toast.LENGTH_LONG).show();
			
		}
	
	}

	
	/*****************************************************/
	/************* MENU AND DIALOGS **********************/
	/*****************************************************/
	
	 /**
     * This method will prepare the menu with the desired menu-items
     */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		
		super.onPrepareOptionsMenu(menu);
		
		UserState app = ((UserState)FindActivity.this.getApplication());
	
		
		
		//true: if admin logged in
		if(app.getState()){
			//Enable add exam option
			MenuItem itemAddExam = menu.findItem(R.id.itemAddExam);
		    itemAddExam.setVisible(true);
		    itemAddExam.setEnabled(true);
		    //Disable favourite option
			MenuItem itemAddFav = menu.findItem(R.id.itemFav);
		    itemAddFav.setVisible(false);
		    itemAddFav.setEnabled(false);
		    //Enable logout
		    MenuItem itemLogout = menu.findItem(R.id.itemlogout);
		    itemLogout.setVisible(true);
		    itemLogout.setEnabled(true);
		    //disable login
		    MenuItem itemLogin = menu.findItem(R.id.itemLogIn);
		    itemLogin.setVisible(false);
		    itemLogin.setEnabled(false);
			
		}else{
			
			//Disable add exam option
			MenuItem itemAddExam = menu.findItem(R.id.itemAddExam);
		    itemAddExam.setVisible(false);
		    itemAddExam.setEnabled(false);
		    //Disable favourite option
			MenuItem itemAddFav = menu.findItem(R.id.itemFav);
		    itemAddFav.setVisible(true);
		    itemAddFav.setEnabled(true);
		    //Enable logout
		    MenuItem itemLogin = menu.findItem(R.id.itemLogIn);
		    itemLogin.setVisible(true);
		    itemLogin.setEnabled(true);
		    //disable login
		    MenuItem itemLogout = menu.findItem(R.id.itemlogout);
		    itemLogout.setVisible(false);
		    itemLogout.setEnabled(false);
		
			
		}
		
		return true;
	}
	/**
	 * Creates the menu, with the menu-items specified in the menu xml file
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}


	/**
	 * Action for a selected menu item
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		UserState app = ((UserState)FindActivity.this.getApplication());
		switch(item.getItemId()){
		
		//Favorite button
		case R.id.itemFav:
			startActivity(new Intent(this,FavouriteActivity.class));
			break;
		//Find button
		case R.id.itemFind:
			startActivity(new Intent(this, FindActivity.class));
			break;
			
		//Add Exam button
		case R.id.itemAddExam:
			startActivity(new Intent (this,AddExamActivity.class ));
			break;
		//Login user	
		case R.id.itemLogIn:
			startActivity(new Intent(this,LoginActivity.class));
			break;
		//logout user	
		case R.id.itemlogout:
			app.logoutUser();
			break;
			
		}
	
		return true;
	}
	/**
	 * Creates a progressdialog, that is displayed  when the user makes a search	
	 */
	  @Override
	  protected Dialog onCreateDialog(int id) {
	   
		  switch (id) {
	    case DIALOG_ID: {
	    	
	      ProgressDialog dialog = new ProgressDialog(this);
	      
	      dialog.setMessage(FindActivity.this.getString(R.string.dialogmsg));
	      
	      dialog.setIndeterminate(true);
	      
	      dialog.setCancelable(true);
	      
	      return dialog;
	    }
	    
		  }

	    return null;
	  }
	
	/*****************************************************/
	/************** PRIVATE METHODS **********************/
	/*****************************************************/
	
	 /**
     * The internal method will "connect" the input/output components
     * of the GUI for this activity for use in this code
     */
    private void AttachGUIcomponents(){
    	
        editSearch = (EditText) findViewById(R.id.etFind);
        buttonFind = (Button) findViewById(R.id.bFind);
    	
    }
	/**
	 *  After retrieving results from the server move to next activity
	 * @param list the found exams
	 */
		private void moveToNextActivity(ArrayList<Exam> resultlist){
			
			//Create new intent, move to the result list for reviewing the searched exams
			Intent intent = new Intent(FindActivity.this, ResultActivity.class);
			//Place the found exams to the next activity
			intent.putParcelableArrayListExtra(
					FindActivity.this.getString(R.string.keyResultList), resultlist );
			//Start the new activity
			FindActivity.this.startActivity(intent); 
			
			
		}
		
		
	/*****************************************************/
	/************** ASYNCTASKS      **********************/
	/*****************************************************/
			
		
	/**
	 * This internal class, will help us create an asynctask when we search for an exam
	 * in the server database, instead of burden the UI thread	
	 * @author Joseph
	 *
	 */
	private class SearchForexam extends AsyncTask<String,Integer,Exam>{

		
		/**
		 * This method will perform a search on the database
		 * In this asynctask the courseid is used to retrieve the
		 * exam
		 */
		@Override
		protected Exam doInBackground(String... userdata) {
			Exam exam = null;
			
			try {
				//Search for the exam online
				exam = ExternalStorage.findById(userdata[0]);
				
			} catch (java.net.SocketTimeoutException e){
				  
				err_msg = "The server is busy, Try later!";
			}catch (Exception e) {
				exam = null;
			}
			
			return exam;
		}

		/**
		 * This method is executed after doInBackground and will present the result 
		 * from doInBackground
		 */
		@Override
		protected void onPostExecute(Exam result) {
			
			
			super.onPostExecute(result);
			//Remove the progressdialog
			dismissDialog(DIALOG_ID);
			
			//If some error occurs
			if(err_msg.length() != 0){
				
				Toast.makeText(FindActivity.this,err_msg,Toast.LENGTH_LONG).show();
				//Reset the string
				err_msg = "";
			}else{
				//Start next activity and present the result
				ArrayList<Exam> searchList = new ArrayList<Exam>();
				if(result !=null){
				searchList.add(result);
				}
				FindActivity.this.moveToNextActivity(searchList);
				
			}
			
			
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
		
		
	
	}
	/**
	 * This internal class, will help us create an asynctask when we search for exams
	 * based on course name in the server database, instead of burden the UI thread	
	 * @author Joseph
	 *
	 */
	private class SearchForexams extends AsyncTask<String,Integer,ArrayList<Exam>>{

		/**
		 * This method will search the database after a given coursename
		 * The method will return a list containing the found exams
		 */
		@Override
		protected ArrayList<Exam> doInBackground(String... userdata) {
			ArrayList<Exam>  exams = null;
			
			try {

				exams = (ArrayList<Exam>) ExternalStorage.findByName(userdata[0]);
			} catch (java.net.SocketTimeoutException e){
				  
				err_msg = "The server is busy, Try later!";
			}catch (Exception e) {
				err_msg = "No internet";
			}
			
			return exams;
		}
				
		/**
		 * This method is executed after doInBackground and will present the result 
		 * from doInBackground
		 */
		@Override
		protected void onPostExecute(ArrayList<Exam> result) {
			
			
			super.onPostExecute(result);
			dismissDialog(DIALOG_ID);
			
			
			//If some error occurs
			if(err_msg.length() != 0){
				
				Toast.makeText(FindActivity.this,err_msg,Toast.LENGTH_LONG).show();
				//Reset the string
				err_msg = "";
			
			}else{
				
				//Display the result
				FindActivity.this.moveToNextActivity(result);
				
			}
			
			
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
		
		
		
		
	}

}